import {Component, OnInit, ViewChild} from '@angular/core';
import {Globals} from '../../globals';
import {RoleIdEnum} from '../../enums/role-id.enum';
import {Consts} from '../../config/consts';
import {PageHelper} from '../../utils/page-helper-model';
import {ApiUrl} from '../../config/api-url';
import {BaseService} from '../../shared/service/base.service';
import {ActivatedRoute, Router} from '@angular/router';
import {FormBuilder, FormGroup} from '@angular/forms';
import {MyDateModel} from '../../models/my-date.model';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';


@Component({
  selector: 'app-stmt-result',
  templateUrl: './stmt-result.component.html',
  styleUrls: ['./stmt-result.component.less']
})
export class StmtResultComponent implements OnInit {

  isMobile = Globals.isMobile();
  // 加载状态
  isSpinning: boolean = false;
  // 角色
  roleId: number;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  // 运营商
  userList: [];
  // 开始日期类型
  startDateTimeType = 'start';
  // 结束日期类型
  endDateTimeType = 'end';
  // 支付完成时间（开始时间）
  gmtPaymentStart: Date;
  // 支付完成时间（结束时间）
  gmtPaymentEnd: Date;

  status = '-1';
  // 分页
  pageHelper: PageHelper = new PageHelper;

  listOfData: [];

  formModel: FormGroup;
  userInfo: any;
  payCompanyCodeList: any;

  constructor(private baseService: BaseService, private http: HttpClient, private router: Router, private fb: FormBuilder) {
  }

  submitForm() {
    this.initStmtResultList();
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.buildForm();
    this.gmtPaymentStart = this.baseService.zorro.getDateTime().startToday;
    this.gmtPaymentEnd = this.baseService.zorro.getDateTime().endToday;
    this.formModel.get('payDateStart').setValue(this.gmtPaymentStart);
    this.formModel.get('payDateEnd').setValue(this.gmtPaymentEnd);
    this.roleId = JSON.parse(sessionStorage.getItem(Consts.USER_INFO)).roleId;
    this.findPayCompanyCodeList();
    this.initStmtResultList();
    this.getAllUserOfName();
  }

  buildForm() {
    this.formModel = this.fb.group({
      merchantId: ['', []],
      payCompanyCode: ['', []],
      payDateStart: ['', []],
      payDateEnd: ['', []],
      payStatus: ['', []],
      userId: ['', []],
    });
  }
  getAllUserOfName() {
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=0').subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }
  initStmtResultList() {
    this.pageHelper.currentPage = 1;
    this.findStmtResult();
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.findStmtResult();
  }
  //Blob文件转换下载
  downFile(result, fileName, fileType?) {
    var data = result.body;
    var blob = new Blob([data], {type: fileType || data.type});
    var objectUrl = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', fileName);
    a.click();
    URL.revokeObjectURL(objectUrl);
  }
  requestBlob(url: any, data?: any): Observable<any> {
    return this.http.request('post', url, {
      body: data,
      observe: 'response',
      responseType: 'blob',
    });
  }
  export(url: any, fileName: string, fileType?: any) {
    this.requestBlob(url, {}).subscribe(result => {
      this.downFile(
        result,
        fileName,
        fileType ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
    });
  }
  exportTheOrder(){
    this.baseService.layer.modalConfirm('确定导出数据吗？', confirm => {
      if (confirm) {
        this.baseService.post(ApiUrl.StmtResultUrl + '/exportTheOrder', this.formModel.value).subscribe(
          res => {
            if (res.status == 0) {
              this.export(res.data.downloadUrl, res.data.fileName);
            } else {
              this.baseService.layer.messageError(res.msg);
            }
          }
        );
      }
    });
  }
  onPageSizeChange(pageSize: any){
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.findStmtResult();
  }
  findStmtResult() {
    this.baseService.findListByMuchCondition(ApiUrl.StmtResultUrl + '/findStmtResult', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.pageHelper.numPages = data.data.pages;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  findPayCompanyCodeList() {
    this.baseService.get(ApiUrl.payCompanyUrl + '/findPayCompanyList').subscribe(
      data => {
        if (data.status == 0) {
          this.payCompanyCodeList = data.data;
          let item = {
            name: '不限',
            code: '-1'
          };
          this.payCompanyCodeList.unshift(item);
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  gmtPaymentTime($event: MyDateModel) {
    if ($event.type == 'start') {
      this.formModel.get('payDateStart').setValue($event.date);
    } else if ($event.type == 'end') {
      this.formModel.get('payDateEnd').setValue($event.date);
    }
  }
}
